4

1.html部分,选择文件(excel为例)

<form id="uploadForm" class='display_inline' enctype="multipart/form-data">
    <input id="orderFile" type="file" class="clip_0" name="file" accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"/>
</form>

2.js中上传文件部分,主要用到的是jequery和FormData

var formData = new FormData($('#uploadForm')[0]);
formData.append("mapType", "baidu");

$.ajax({
    url: '/upload/order',
    type: 'POST',
    data: formData,
    processData: false, //  告诉jquery不要处理发送的数据
    contentType: false // 告诉jquery不要设置content-Type请求头
}).done(function (res) {

}).fail(function (res) {
    console.log("失败");
});

3.后台node接收部分,解析excel用的是"node-xlsx"

const express = require('express');
const fs = require('fs');
const formidable = require('formidable');
const xlsx = require('node-xlsx');

const router = express.Router();

router.post('/order', (req, res) => {
    console.log(' ########## POST /upload ####### ');

    let fileTypeError = false;
    const targetPath = `${__dirname}/upload`;
    const form = new formidable.IncomingForm();
    form.encoding = 'utf-8';
    form.keepExtensions = true;
    form.maxFieldsSize = 10 * 1024 * 1024;
    form.uploadDir = targetPath;

    const files = [];
    const fields = [];

    let mapType = 'gaode';

    form.on('field', (field, value) => { // 上传的相关参数("mapType", "baidu")
        if (field === 'mapType')mapType = value;
        fields.push([field, value]);
    });

    form.on('file', (field, file) => { // 接收文件触发
        console.log(`upload file: ${file.name}`);
        // 判断文件类型是否是xlsx
        if (file.type !== 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') {
            fileTypeError = true;
        }
        files.push([field, file]);
    });
    form.on('end', () => {
        // 遍历上传文件
        let fileName = '';
        let obj = '';
        const folderExists = fs.existsSync(targetPath);
        if (folderExists) {
            const dirList = fs.readdirSync(targetPath);
            dirList.forEach(async (item) => {
                if (!fs.statSync(`${targetPath}/${item}`).isDirectory()) {
                    console.log(`parse item:${targetPath}/${item}`);
                    fileName = `${targetPath}/${item}`;
                    if (!fileTypeError) {
                        // 解析excel
                        obj = xlsx.parse(fileName, {
                            cellDates: true
                        });

                        console.log(JSON.stringify(obj));
                        res.send({
                            code: 10000,
                            msg: '成功解析数据',
                            resOrders: resOrderObjs
                        });
                    } else {
                        res.send({
                            code: 20003,
                            msg: '文件格式不正确'
                        });
                    }
                    fs.unlinkSync(fileName); // delete file
                }
            });
        } else {
            res.send({
                rtnCode: '1',
                rtnInfo: '系统错误'
            });
        }
    });
    form.on('error', (err) => {
        res.send({
            rtnCode: '1',
            rtnInfo: '上传出错'
        });
    });
    form.on('aborted', () => {
        res.send({
            rtnCode: '1',
            rtnInfo: '放弃上传'
        });
    });
    form.parse(req);
});

参考链接:
http://www.cnblogs.com/lyr121...
https://lipeishang.github.io/...


小谷xg
2.3k 声望297 粉丝

明月清风自在怀,任重道远常心态。坎坷人生从容走,否极自有安泰来。